const app = getApp()

Page({
    data: {
        ids:"",
        service: false,
        markers: [], //地图参数：
        latitude: "", //纬度 
        longitude: "", //经度
        user: {},
        city: {},
        lat: '',
        lon: '',
        order_id: 0,
        i_mark:'',
        i_distance:'',
        i_price:'',
        i_search:'',
        // 轮播
        imgUrls: [],
        store_label:[],
        indicatorDots: true,
        vertical: true,
        autoplay: true,
        interval: 2000,
        duration: 500,
        // 公告
        msgList: [],
        // 首页列表
        tabTxt: ['智能排序', '距离', '价格','筛选'],//分类
        tab: [true, true, true,true],
        tab_active: [true, true, true,true],
        pinpaiList: [{ 'id': '1', 'title': '品牌1' }, { 'id': '2', 'title': '品牌2' }],
        pinpai_id: 0,//品牌
        pinpai_txt: '',
        jiage_id: 0,//价格
        jiage_txt: '',
        xiaoliang_id: 0,//销量
        xiaoliang_txt: '',
        sx_id: 0,//销量
        sx_txt: '',
        details: [],
        circular: true, //是否采用衔接滑动
        indicatorDots: true, //是否显示面板指示点
        scrollTop: '', //滑动的距离
        navFixed: false, //导航是否固定
        currentData: 0,
        canIUseGetUserProfile: false,
    },

    // 下面不是的
    // 轮播图
    getBanner: function (e) {
        app.ajax({
            url: '/api/index/getIndexHeaderAggregate',
            success: res => {
                if (res.code == 1) {
                    this.setData({
                        imgUrls: res.data.banner_list,
                        msgList:res.data.notice,
                        order_info:res.data.order
                    })
                }
            }
        })
    },
     // 选项卡
  filterTab: function (e) {
    var data = [true, true, true,true], tab_active = [true, true, true,true], index = e.currentTarget.dataset.index;
    data[index] = !this.data.tab[index];
    tab_active[index] = !this.data.tab_active[index];
    this.setData({
      tab: data,
      tab_active:tab_active
    })
  },
  //监听滑动
  layoutScroll: function(e) {
    this.data.scrollTop = this.data.scrollTop * 1 + e.detail.deltaY * 1;
    // console.log(this.data.scrollTop)
    // console.log(this.data.navFixed)
    /** 我这里写了固定值 如果使用rpx 可用query可以动态获取其他的高度 然后修改这里值 */
    /** 获取方法参考文档 */

    /** scrollTop 在模拟器上检测不是太灵敏 可在真机上测试 基本上不会出现延迟问题 */
    var navtopHeight = 100;
    if (this.data.scrollTop >= -navtopHeight) {
    //   this.setData({
    //     navFixed: false
    //   })
    // } else {
    //   this.setData({
    //     navFixed: true
    //   })
    }
  },
  //筛选项点击操作
  filter: function (e) {
    var self = this,
     id = e.currentTarget.dataset.id,
      txt = e.currentTarget.dataset.txt, 
      distance = e.currentTarget.dataset.distance, 
      price = e.currentTarget.dataset.price, 
      lableid = e.currentTarget.dataset.lableid, 
      comparison_operator = '',
      tabTxt = this.data.tabTxt;
    if(distance == 1){
        comparison_operator = '{"comparison_operator":"lt","num_arr":[3000]}'
    }else if(distance == 2){
        comparison_operator = '{"comparison_operator":"between","num_arr":[3000,5000]}'
    }
    else if(distance == 3){
        comparison_operator = '{"comparison_operator":"between","num_arr":[5000,10000]}'
    }
    else if(distance == 4){
        comparison_operator = '{"comparison_operator":"gt","num_arr":[10000]}'
    }else{
        comparison_operator = ''
    }
    switch (e.currentTarget.dataset.index) {
      case '0':
        tabTxt[0] = txt;
        self.setData({
          tab: [true, true, true,true],
          tabTxt: tabTxt,
          pinpai_id: id,
          pinpai_txt: txt,
          i_mark:price,
          i_price:price,
          i_distance:comparison_operator,
          xiaoliang_id: id,
          xiaoliang_txt: txt,
        });
        break;
      case '1':
        tabTxt[1] = txt;
        self.setData({
          tab: [true, true, true,true],
          tabTxt: tabTxt,
          jiage_id: id,
          jiage_txt: txt,
          i_distance:comparison_operator
        });
        break;
      case '2':
        tabTxt[2] = txt;
        self.setData({
          tab: [true, true, true,true],
          tabTxt: tabTxt,
          xiaoliang_id: id,
          xiaoliang_txt: txt,
          i_price:price
        });
        break;

        case '3':
            tabTxt[3] = txt;
            self.setData({
              tab: [true, true, true,true],
              tabTxt: tabTxt,
              sx_id: id,
              sx_txt: txt,
              i_search:price,
              i_price:price,
              i_distance:comparison_operator,
              lableid:lableid
            });
            break;
        }
    //数据筛选
    self.getStores();
  },
 
  //加载数据
  getDataList: function () {
  

        //调用数据接口，获取数据
        wx.setStorageSync('location', {
            lat: res.latitude,
            lon: res.longitude,
        });
        var city = wx.getStorageSync('city');
        if (city) {
            this.setData({
                city: city
            });
       
            this.getStores();
        } else {
            this.getCity();
        }
    },
    //事件处理函数
    btnOK:function(event){
        this.ids = event.currentTarget.dataset.id;
       if(this.ids==1){
        wx.navigateTo({
            url: '/pages/join/join'
        })
      
       }else{
        wx.navigateTo({
            url: '/pages/coupon/coupon'
        })
       }
    },
    handle_service: function() {
        this.setData({
            service: true
        })
    },
    stopBubb: function() {
        return false
    },

    close_layer: function() {
        this.setData({
            service: false,
        })
    },
    select_city: function() {
        wx.navigateTo({
            url: '/pages/select_city/select_city'
        })
    },
    search_result: function() {
        // if(!this.data.user.mobile) return false;
        wx.navigateTo({
            url: '/pages/search_info/search_info'
        })
    },
    opening_code: function() {
        wx.navigateTo({
            url: '/pages/opening_code/opening_code?order_id=' + this.data.order_id
        })
    },
    history_order: function() {
        wx.navigateTo({
            url: '/pages/history_order/history_order'
        })
    },
    callPhone(e) {
        var tel = wx.getStorageSync('tel');
        if(tel)
        wx.makePhoneCall({
            phoneNumber: tel,
            success: function() {},
        })
    },
    callStore(e) {
      var tel = e.target.dataset.tel;
      if(tel)
      wx.makePhoneCall({
          phoneNumber: tel,
          success: function() {},
      })
  },
  listenerBtnGetLocation:function(e){
    var lat = e.target.dataset.lat;
    var tel = e.target.dataset.lon;
    var name = e.target.dataset.name;
    var address = e.target.dataset.address;
    console.log(lat)
    console.log(tel)
    wx.getLocation({
      //定位类型 wgs84, gcj02
      type: 'gcj02',
      success: function(res) {
        console.log(res)
        //return false
        wx.openLocation({
          //当前经纬度
          latitude: res.latitude,
          longitude: res.longitude,
          //缩放级别默认28
          scale: 28,
          //位置名
          name: name,
          //详细地址
          address: address,
          // //成功打印信息
          // success: function(res) {
          //   console.log(res)
          // },
          // //失败打印信息
          // fail: function(err) {
          //   console.log(err)
          // },
          // //完成打印信息
          // complete: function(info){
          //   console.log(info)
          // },
        })
 
      },
      fail: function(err) {
        console.log(err)
      },
      complete: function(info) {
        console.log(info)
      },
    })
    
  },
    use_explain: function() {
        wx.navigateTo({
            url: '/pages/use_explain/use_explain'
        })
    },
    common_problem: function() {
        wx.navigateTo({
            url: '/pages/common_problem/common_problem'
        })
    },
    //首页
    goindex: function(e) {
        wx.redirectTo({
            url: '/pages/index/index'
        })
    },
    select_teaRoom: function() {
        wx.navigateTo({
            url: '/pages/search_result/search_result'
        })
    },
     //我的订单
     myorder: function() {
        wx.redirectTo({
            url: '/pages/my_order/my_order'
        })
    },
    //我的
    my: function() {
        wx.redirectTo({
            url: '/pages/my/my'
        })
    },
    moveToLocation: function() {
        var mapCtx = wx.createMapContext('map'); //wxml中map标签的id值
        mapCtx.moveToLocation();
    },
    markertap: function(e){
        if(!this.data.user.mobile){
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            })
            return false;
        }
        console.log(e);
        if(e.markerId){
            wx.navigateTo({
              url: '/pages/book/book?id=' + e.markerId
            })
        }
    },
    onLoad: function(options) {
        if (wx.getUserProfile) {
            this.setData({
                canIUseGetUserProfile: true
            })
        }
        this.getLocation();
        this.getSite();

        // 定时获取店铺列表
        // setInterval(()=>{
            
        // },5000)
        this.getStores();
    },
    getSite: function(){
        app.ajax({
            url: '/api/index/getSite',
            success: res => {
                if(res.code == 1){
                    var site = res.data;
                    wx.setStorageSync('tel', site.tel[0]);
                    wx.setStorageSync('instructions', site.instructions);
                    wx.setStorageSync('about', site.about);
                    wx.setStorageSync('name', site.name);
                    wx.setStorageSync('explain', site.explain);
                }
            }
        })
    },
    // 获取首页标签
    getLabelList: function(){
        app.ajax({
            url: '/api/index/getLabelList',
            success: res => {
                if(res.code == 1){
                    wx.setStorageSync('store_label', res.data)
                    this.setData({
                        store_label: res.data,
                    });
                }
            }
        })
    },
    getLocation: function() {
        wx.getLocation({
            success: res => {
                this.setData({
                    lat: res.latitude,
                    lon: res.longitude,
                });
                wx.setStorageSync('location', {
                    lat: res.latitude,
                    lon: res.longitude
                });
                var city = wx.getStorageSync('city');
                if (city) {
                    this.setData({
                        city: city
                    });
                    this.getStores();
                } else {
                    this.getCity();
                }
            },
        })
    },
    getCity: function() {
        app.ajax({
            url: '/api/index/getCity',
            data: {
                lat: this.data.lat,
                lon: this.data.lon
            },
            success: res => {
                if (res.code == 1) {
                    var city = res.data;
                    wx.setStorageSync('city', city);
                    this.setData({
                        city: city
                    });
                    this.getStores();
                }
            }
        })
    },
    getStores: function() {
        app.ajax({
            url: '/api/index/stores',
            data: {
                lat: this.data.lat,
                lon: this.data.lon,
                city_id: this.data.city.id,
                mark:this.data.i_mark,
                distance_where:this.data.i_distance,
                order_price:this.data.i_price,
                search:this.data.i_search,
                label_id:this.data.lableid,
            },
            success: res => {
                if (res.code == 1) {
                    wx.setStorageSync('stores', res.data);
                    var markers  =  [];
                    var address = [];
                    for (var i in res.data) {
                        var row = res.data[i];    
                        address.push({
                          id: row.id,
                          address: row.address,
                          lat: row.lat,
                          lon: row.lon,
                          name: row.name
                        });

                        if(row.rooms.length > 0){
                            markers.push({
                                id: row.rooms[0].id,
                                latitude: parseFloat(row.lat),
                                longitude: parseFloat(row.lon),
                                iconPath: '/images/marker.png',
                                width: 24,
                                height: 23,
                                callout: {
                                    content: row.name + '(' + row.distance + ')',
                                    color: '#fff',
                                    fontSize: 10,
                                    borderRadius: 5,
                                    bgColor: '#1CA3BF',
                                    padding: 5,
                                    display: 'ALWAYS'
                                }
                            });
                        }

                   
                    }
                    this.setData({
                        markers: markers,
                        details:res.data,
                        address:address
                    })
                } else {
                    wx.removeStorageSync('stores');
                    // wx.showToast({
                    //     title: '空空如也',
                    //     icon: 'none'
                    // })
                    this.setData({
                        markers: [],
                        details:[]
                    })
                }
            }
        })
    },
    onShow: function() {
        var city = wx.getStorageSync('city');
        if (city && city.id != this.data.city.id) {
            this.setData({
                city: city
            });
            if (this.data.lat && this.data.lon) this.getStores();
        }

        this.userinfo();

        this.getNewOrder();
        this.getBanner();
        this.getLabelList();


    },



    userinfo: function() {
        app.ajax({
            url: '/api/user/userinfo',
            success: res => {
                if (res.code == 1) {
                    wx.setStorageSync('user', res.data);
                    this.setData({
                        user: res.data
                    })
                }
            }
        })
    },
    getNewOrder: function(){
        app.ajax({
            url: '/api/user/newOrder',
            success: res => {
                if(res.code == 1){
                    this.setData({
                        order_id: res.data
                    })
                }
            }
        })
    },
    login: function(e) {
        console.log(e);

        console.log(this.data.canIUseGetUserProfile);
        if (this.data.canIUseGetUserProfile){
            console.log('getUserProfile')
            wx.getUserProfile({
                desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                success: (res) => {
                    console.log(res)
                    if (!res.userInfo) {
                        wx.showToast({
                            title: '未获取到用户信息',
                            icon: 'none'
                        });
                        return;
                    }
                    wx.setStorageSync('userinfo', res.userInfo);
                    wx.navigateTo({
                        url: '/pages/login/login'
                    })
                }
            })
        } else {
            if (!e.detail.userInfo) {
                wx.showToast({
                    title: '未获取到用户信息',
                    icon: 'none'
                });
                return;
            }
            wx.setStorageSync('userinfo', e.detail.userInfo);
            wx.navigateTo({
                url: '/pages/login/login'
            })
        }

    },
    xiangqing: function (e) {
        var id = e.target.dataset.id;
        wx.navigateTo({
            url: '/pages/xiangqing/xiangqing?id=' +id,
        })

    },
    xiangqing1: function (e) {
        var id = e.currentTarget.dataset.id;
        console.log(e);
        console.log(id);
        wx.navigateTo({
            url: '/pages/xiangqing/xiangqing?id=' +id,
        })
    },
    order_subscribe:function(e){
        var id = e.target.dataset.id;
        wx.navigateTo({
            url: '/pages/unsettled/unsettled?order_id=' +id,
            // url: '/pages/opening_code/opening_code?order_id=' +id,
        })
    },
    //公告弹窗
    openTip:function(e){
      var name = e.currentTarget.dataset.name || ''
      wx.showModal({
        title: '详情',
        content: name,
        showCancel:false,
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },

    goyz: function(e) {
      var index = e.currentTarget.dataset.t;
      if(index == 1){
        wx.navigateTo({
          url: '/pages/duihuan/duihuan?dhkey=1'
      });
      }
      if(index == 2){
        wx.navigateTo({
          url: '/pages/duihuan/duihuan?dhkey=2'
      });
      }
      if(index == 3){
        wx.navigateTo({
          url: '/pages/account_chongzhi/account_chongzhi'
      });
      }
      if(index == 4){
        wx.navigateTo({
          url: '/pages/company_intr/company_intr'
      });
      }
  },
    //   时间选择器
    bindTimeChange: function(e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
        time: e.detail.value
        })
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})